/**
 * LoginServiceImpl.java
 * Created at 2016-5-5
 * Created by TangSanlin
 * Copyright (C) 2016 BROADTEXT SOFTWARE, All rights reserved.
 */
package com.broadtext.rms.system.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.broadtext.common.exp.DaoException;
import com.broadtext.common.exp.ServiceException;
import com.broadtext.common.utils.StringUtils;
import com.broadtext.rms.session.ActionConstants;
import com.broadtext.rms.system.dao.ISysResourceDao;
import com.broadtext.rms.system.dao.ISysRoleDao;
import com.broadtext.rms.system.dao.ISysUserDao;
import com.broadtext.rms.system.dao.IVsysUserDao;
import com.broadtext.rms.system.model.*;
import com.broadtext.rms.system.service.ILoginService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 
 * <p>
 * ClassName: LoginServiceImpl
 * </p>
 * <p>
 * Description: 用户登录服务实现类
 * </p>
 * <p>
 * Author: TangSanlin
 * </p>
 * <p>
 * Date: 2016-5-17
 * </p>
 */
@Service("loginService")
public class LoginServiceImpl implements ILoginService {
    /**
     * 日志信息
     */
    private static Logger logger = LoggerFactory.getLogger(LoginServiceImpl.class);
    
    /**
     * 用户表DAO
     */
    @Autowired
    @Qualifier("sysUserDao")
    private ISysUserDao sysUserDao;
    
    /**
     * 用户表DAO
     */
    @Autowired
    @Qualifier("vSysUserDao")
    private IVsysUserDao vSysUserDao;
    
    /**
     * 角色表DAO
     */
    @Autowired
    @Qualifier("sysRoleDao")
    private ISysRoleDao sysRoleDao;
    
    /**
     * 资源表DAO
     */
    @Autowired
    @Qualifier("sysResourceDao")
    private ISysResourceDao sysResourceDao;

    @Override
    public SysUser findUser(String loginName) {
        List<SysUser> list;
        list = new ArrayList<SysUser>();
        try {
            list = this.sysUserDao.selectByUserName(loginName);
        } catch (DaoException e) {
            logger.debug(e.getMessage());
            e.printStackTrace();
        }
        if (list.isEmpty()) {
            return null;
        } else {
            return list.get(0);
        }
    }
    
    @Override
    public VSysUsers findVuser(String loginName) {
        List<VSysUsers> list;
        list = new ArrayList<VSysUsers>();
        try {
            list = this.vSysUserDao.selectByUserName(loginName);
        } catch (DaoException e) {
            logger.debug(e.getMessage());
            e.printStackTrace();
        }
        if (list.isEmpty()) {
            return null;
        } else {
            return list.get(0);
        }
    }

    @Override
    public List<SysRole> selectRoleByUserId(String userId) {
        List<SysRole> list;
        list = new ArrayList<SysRole>();
        try {
            list = this.sysRoleDao.selectRoleByUserId(userId);
        } catch (DaoException e) {
            logger.debug(e.getMessage());
            e.printStackTrace();
        }
        return list;
    }
    
    
    @Override
    public SysResource[] getHavResByLoginName(String loginName) throws DaoException {
        List<SysResource> list;
        list = new ArrayList<SysResource>();
        if (ActionConstants.ADMIN_USER.equals(loginName)) {
            list = this.sysResourceDao.selectAllResource();
        }
        else {
            list = this.sysResourceDao.selectResourceByLoginName(loginName);
        }
        return list.toArray(new SysResource[0]);
    }
    
    @Override
    //TODO 1
    public JSONArray getUserRes(String userId) throws DaoException {
        List<SysResource> list;
        list = new ArrayList<SysResource>();
        //模块资源列表
        list = this.sysResourceDao.selectResourceByUserId(userId);
        JSONArray resArray;
        resArray = new JSONArray();
        resArray = getRes(list, userId);
        return resArray;
    }
    
    /**
     * 
     * <p>Description: 获取用户资源</p>
     * @param list 
     * @param userId    
     * @return 资源列表
     * @throws DaoException 
     */
    //TODO 2
    public JSONArray getRes(List<SysResource> list, String userId) throws DaoException {
        JSONArray resArray;
        resArray = new JSONArray();
        JSONObject resObject;
        Map<String, Object> map;
        map = new HashMap<String, Object>();
        map.put("userId", userId);
        for (SysResource res : list) {
            resObject = new JSONObject();
            map.put("parentId", res.getPkId());
            if ("3".equals(res.getResType())) {
                resObject.put("btnId", res.getResUrl());
            } else if ("2".equals(res.getResType())) {
                List<SysResource> btnList;
                btnList = new ArrayList<SysResource>();
                btnList = this.sysResourceDao.selectResourceByMap(map);
                resObject.put("id", res.getResUrl());
                resObject.put("text", res.getResName());
                resObject.put("href", res.getResUrl());
                resObject.put("isLevel", "1");
                resObject.put("isSubMenu", "1");
                resObject.put("buttons", this.getRes(btnList, userId));
            } else {
                List<SysResource> resList;
                resList = new ArrayList<SysResource>();
                resList = this.sysResourceDao.selectResourceByMap(map);
                resObject.put("id", res.getResUrl());
                resObject.put("text", res.getResName());
                resObject.put("iconClass", res.getRemark());
                resObject.put("isLevel", "0");
                resObject.put("isSubMenu", "0");
                resObject.put("childs", getRes(resList, userId));
            }
            resArray.add(resObject);
        }
        return resArray;
    }

    @Override
    public boolean modifyPass(SysUser user) throws ServiceException {
        try {
            return this.sysUserDao.modityUserPass(user);
        } catch (DaoException e) {
            throw new ServiceException(e);
        }
    }

    /**
     * 
     * <p>Description: 获取账户使用期限</p>
     * @param loginName    
     * @return boolean
     * @throws DaoException 
     */
    @Override
    public boolean getAccountValidity(String loginName) throws ServiceException {
        try {
            List<SysAccountValidity> list = this.sysUserDao.getAccountValidity(loginName);
            if(list!=null&&list.size()>0){
                SysAccountValidity account =list.get(0);
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = new Date();
                Date startDate=null;
                Date endDate=null;
                if(StringUtils.isNotBlank(account.getAccountStartDateStr())){
                    startDate = format.parse(account.getAccountStartDateStr());
                }
                if(StringUtils.isNotBlank(account.getAccountEndDateStr())){
                    endDate = format.parse(account.getAccountEndDateStr());
                }
                //前后日期都不为空
                if(startDate!=null&&endDate!=null){
                    if(date.getTime()<=endDate.getTime()&&date.getTime()>=startDate.getTime()){
                        return true;
                    }else {
                        return false;
                    }
                }else if(startDate!=null&&endDate==null){
                    if(date.getTime()>=startDate.getTime()){
                        return true;
                    }else {
                        return false;
                    }
                }else if(startDate==null&&endDate!=null){
                    if(date.getTime()<=endDate.getTime()){
                        return true;
                    }else {
                        return false;
                    }
                }else if(startDate==null&&endDate==null) {
                    return true;
                }
                
            }
        } catch (DaoException e) {
            e.printStackTrace();
            throw new ServiceException(e);
        } catch (ParseException e) {
            e.printStackTrace();
            throw new ServiceException(e);
        }
        return true;
    }

    @Override
    public Boolean showMsgReceiveManage(String id) throws DaoException {
        List<SysResource> list = this.sysResourceDao.getMsgReceiveManageResource(id);
        return list != null && list.size() > 0 && list.get(0) != null;
    }
}
